package org.mango.action;

import com.alibaba.fastjson.JSONObject;
import com.mango.validator.util.ValidUtil;
import org.mango.base.BaseAction;
import org.mango.bean.Sort;
import org.mango.id.Tools;
import org.mango.service.SortService;
import org.mango.util.UserUtil;
import org.mango.validator.SortNameValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by meigang on 17/9/8.
 */
@RestController
@RequestMapping("/sort")
public class SortAction extends BaseAction{
    @Autowired
    private SortService sortService;
    @Autowired
    private ValidUtil validUtil;
    @Autowired
    private SortNameValidator sortNameValidator;
    @GetMapping("/list")
    public String list(HttpServletRequest req){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("creator",UserUtil.getSessionUser(req).getId());
        List<Sort> list = sortService.list(map);
        return JSONObject.toJSONString(list);
    }

    @GetMapping("/listAll")
    public String listAll(HttpServletRequest req){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("creator",UserUtil.getSessionUser(req).getId());
        List<Sort> list = sortService.listAll(map);
        return JSONObject.toJSONString(list);
    }

    @GetMapping("/getById")
    public String getById(String id){
        Sort sort = sortService.getById(id);
        return JSONObject.toJSONString(sort);
    }

    @GetMapping("/gridNum")
    public int gridNum(String id){
        return sortService.gridNum(id);
    }

    @RequestMapping("/add")
    public String add(Sort sort,HttpServletRequest req){
        sort.setCreateTime(new Date());
        sort.setCreator(UserUtil.getSessionUser(req).getId());
        List<String> msgList = validUtil.validateAll(sort,false,sortNameValidator);
        if(msgList!=null){
            return this.ajaxJson(300,msgList);
        }else {
            sort.setId(Tools.genId()+"");
            sortService.add(sort);
            return this.ajaxJson(200);
        }
    }

    @RequestMapping("/edit")
    public String edit(Sort sort,HttpServletRequest req){
        sort.setLastEditTime(new Date());
        sort.setEditor(UserUtil.getSessionUser(req).getId());
        List<String> msgList = validUtil.validateAll(sort,false,sortNameValidator);
        if(msgList!=null){
            return this.ajaxJson(300,msgList);
        }else {
            sortService.update(sort);
            return this.ajaxJson(200);
        }

    }

    @RequestMapping("/delete")
    public String edit(String id){
        sortService.delete(id);
        return this.ajaxJson(200);
    }


    @GetMapping("/html")
    public String index() {
        this.setAttr("ctx",this.getCtx());
        return "demo";
    }
}
